<template>
  <div ref="wrapperRef" class="flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <NCard title="管理员管理" :bordered="false" size="small" class="sm:flex-1-hidden card-wrapper">
      <template #header-extra>
        <TableHeaderOperation v-model:columns="columnChecks" :disabled-delete="checkedRowKeys.length === 0"
          :loading="loading" @add="handleAdd" @refresh="getData" />
      </template>
      <NDataTable v-model:checked-row-keys="checkedRowKeys" :columns="columns" :data="data" size="small"
        :flex-height="!appStore.isMobile" :scroll-x="1088" :loading="loading" :row-key="row => row.id" remote
        :pagination="pagination" class="sm:h-full" />
    </NCard>
    <NModal v-model:show="visible" :title="title" preset="card" class="w-800px">
      <NScrollbar class="h-480px pr-20px">
        <NForm ref="formRef" :model="model" :rules="rules" label-placement="left" :label-width="100">
          <NGrid responsive="screen" item-responsive>
            <NFormItemGi span="24 m:12" label="用户名" path="username">
              <NInput v-model:value="model.username" placeholder="请输入用户名" />
            </NFormItemGi>
            <NFormItemGi span="24 m:12" label="昵称" path="nickname">
              <NInput v-model:value="model.nickname" placeholder="请输入昵称" />
            </NFormItemGi>
            <NFormItemGi span="24 m:12" label="密码" path="password">
              <NInput v-model:value="model.password" type="password" placeholder="请输入密码" />
            </NFormItemGi>
            <NFormItemGi span="24 m:12" label="用户组" path="group">
              <NSelect v-model:value="model.group" :options="groupOptions" placeholder="请选择用户组" />
            </NFormItemGi>
            <NFormItemGi span="24 m:12" label="邮箱" path="email">
              <NInput v-model:value="model.email" placeholder="请输入邮箱" />
            </NFormItemGi>
            <NFormItemGi span="24 m:12" label="手机号" path="mobile">
              <NInput v-model:value="model.mobile" placeholder="请输入手机号" />
            </NFormItemGi>
          </NGrid>
        </NForm>
      </NScrollbar>
      <template #footer>
        <NSpace justify="end" :size="16">
          <NButton @click="visible = false">取消</NButton>
          <NButton type="primary" @click="handleSubmit">确认</NButton>
        </NSpace>
      </template>
    </NModal>
  </div>
</template>

<script setup lang="tsx">
import { ref, onMounted } from 'vue';
import type { Ref } from 'vue';
import { NButton, NPopconfirm, NTag, NSelect } from 'naive-ui';
import { useBoolean } from '@sa/hooks';
import { useAppStore } from '@/store/modules/app';
import { useTable, useTableOperate } from '@/hooks/common/table';
import { fetchGetAdminList, addAdmin, editAdmin, deleteAdmin } from '@/service/api/index';
import { fetchGetGroups } from '@/service/api/group';
import { log } from 'console';

const appStore = useAppStore();

const { bool: visible, setTrue: openModal } = useBoolean();

const wrapperRef = ref<HTMLElement | null>(null);
const title = ref('');

const groupOptions = ref<{ label: string; value: number }[]>([]);

// 获取用户组数据
async function getGroupOptions() {
  const { response } = await fetchGetGroups();
  console.log(response.data)
  if (response.data.code == 1) {
    const data = (response.data).data.data;
    console.log(data);
    groupOptions.value = data.map((item) => ({
      label: item.name,
      value: item.id
    }));
  }
}

onMounted(() => {
  console.log(111111111);
  getGroupOptions();
});
const model = ref({
  username: '',
  nickname: '',
  password: '',
  group: null,
  email: '',
  mobile: '',
  id: 0,
});
const rules = {};
const { columns, columnChecks, data, loading, pagination, getData, getDataByPage } = useTable({
  apiFn: fetchGetAdminList,
  columns: () => [
    {
      key: 'id',
      title: 'ID',
      align: 'center',
      width: 100,
    },
    {
      key: 'username',
      title: '用户名',
      align: 'center',
      width: 150,
    },
    {
      key: 'nickname',
      title: '昵称',
      align: 'center',
      width: 150,
    },
    {
      key: 'groups_text',
      title: '用户组',
      align: 'center',
      width: 150,
    },
    {
      key: 'email',
      title: '邮箱',
      align: 'center',
      width: 200,
    },
    {
      key: 'mobile',
      title: '手机号',
      align: 'center',
      width: 150,
    },
    {
      key: 'operate',
      title: '操作',
      align: 'center',
      width: 230,
      render: row => (
        <div class="flex-center justify-end gap-8px">
          <NButton type="primary" ghost size="small" onClick={() => handleEdit(row)}>
            编辑
          </NButton>
          <NPopconfirm onPositiveClick={() => handleDelete(row.id)}>
            {{
              default: () => '确定删除吗？',
              trigger: () => (
                <NButton type="error" ghost size="small">
                  删除
                </NButton>
              )
            }}
          </NPopconfirm>
        </div>
      )
    }
  ]
});

const { checkedRowKeys, onBatchDeleted, onDeleted } = useTableOperate(data, getData);

const operateType = ref('add');

function handleAdd() {
  operateType.value = 'add';
  title.value = '新增管理员';
  // 清空model
  model.value = {
    username: '',
    nickname: '',
    password: '',
    group: null,
    email: '',
    mobile: '',
    id: 0,
  };
  openModal();
}

async function handleDelete(id: number) {
  // request
  const { response } = await deleteAdmin(id);
  if (response?.data?.code === 1) {
    window.$message?.success('删除成功！');
    getData();
  } else {
    window.$message?.error(response?.data?.msg || '删除失败');
  }
}

function handleEdit(item: any) {
  console.log(item);
  //item.
  operateType.value = 'edit';
  title.value = '编辑管理员';
  model.value = { ...item };
  openModal();
}

async function handleSubmit() {
  let res;
  if (operateType.value === 'add') {
    res = await addAdmin(model.value,'post');
  } else {
    res = await editAdmin(model.value);
  }
  if (res.response?.data?.code === 1) {
    window.$message?.success(res.response.data.msg);
    visible.value = false;
    getData();
  } else {
    window.$message?.error(res.response?.data?.msg || '操作失败');
  }
}

</script>

<style scoped></style>


